package com.afiorenza.persistence.sample;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import com.afiorenza.persistence.sample.entities.Event;
import com.afiorenza.persistence.sample.entities.Person;

public class EventManager {

	public static void main(String[] args) {

		EventManager mgr = new EventManager();
		// mgr.createAndStoreEvent("Nuevo Evento", new Date());

		List listEvent = mgr.listEvent();
		for (Object object : listEvent) {
			Event e = (Event) object;
			System.out.println(e.getId() + "Nombre: " + e.getTitle());
		}

		mgr.createAndStorePerson(26, "Agustin", "Fiorenza");

		mgr.addPersonToEvent(new Long(1), new Long(1));

		mgr.addEmailToPerson(new Long(1), "agustinf88@gmail.com");

	}

	private void createAndStoreEvent(String title, Date date) {

		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
		session.beginTransaction();

		Event event = new Event();
		event.setTitle(title);
		event.setDate(date);
		session.save(event);

		session.getTransaction().commit();
//		session.close();

	}

	private void createAndStorePerson(int age, String firstName, String lastName) {
		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
		session.beginTransaction();

		Person p = new Person();
		p.setAge(age);
		p.setFirstname(firstName);
		p.setLastname(lastName);

		session.save(p);
		session.getTransaction().commit();
//		session.close();
	}

	private List listEvent() {
		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
		session.beginTransaction();
		List result = session.createQuery("from Event").list();
		session.getTransaction().commit();
//		session.close();

		return result;

	}

	private void addPersonToEvent(Long personId, Long eventId) {

		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
		session.beginTransaction();

		Person aPerson = (Person) session.load(Person.class, personId);
		Event anEvent = (Event) session.load(Event.class, eventId);

		// aPerson.getEvents().add(anEvent);
		aPerson.addToEvent(anEvent);

		session.getTransaction().commit();
//		session.close();

	}

	private void addEmailToPerson(Long personId, String emailAdress) {
		Session session = HibernateUtil.getSessionfactory().getCurrentSession();
		session.beginTransaction();

		Person p = (Person) session.load(Person.class, personId);
		p.getEmailAddresses().add(emailAdress);

		session.getTransaction().commit();
//		session.close();

	}
}
